﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using demo.Common;
using iAgileFramework.DataTransCarrier;

namespace WebApplication1
{
    public class ControllerExtendBase : Controller
    {
        /// <summary>
        /// 模型验证
        /// </summary>
        /// <returns></returns>
        protected ReturnValue ModelValidate()
        {
            var rv = new ReturnValue();
            if (!this.ModelState.IsValid)
            {
                var sb = new StringBuilder();
                foreach (string key in this.ModelState.Keys)
                {
                    if (this.ModelState[key].Errors.Any())
                    {
                        var errorMessageList = from error in this.ModelState[key].Errors
                                               select error.ErrorMessage;

                        sb.Append(string.Join(" ", errorMessageList) + "<br/>");
                    }
                }

                rv.Fail(sb.ToString());
                return rv;
            }
            rv.Success();
            return rv;
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            string message;
            string str2 = filterContext.RouteData.Values["controller"].ToString();
            string str3 = filterContext.RouteData.Values["action"].ToString();
            object obj2 = filterContext.RouteData.DataTokens["area"];
            LogHelper.Error(string.Format("页面未捕获的异常：Area:{0},Controller:{1},Action:{2}", obj2, str2, str3), filterContext.Exception);

            message = "系统内部异常";
            if (WebHelper.IsAjax())
            {
                var rv = new ReturnValue();
                rv.Fail(message);
                filterContext.Result = base.Json(rv);
            }
            else
            {
                var result = new ViewResult
                {
                    ViewName = "HandleError"
                };

                filterContext.Result = result;
            }
            filterContext.HttpContext.Response.StatusCode = 200;
            filterContext.ExceptionHandled = true;
        }

    }
}